package util.webSearch;

/**
 * 
 * Based one Ryan Kennedy Yahoo! java API demo
 * 
 * @author Sergio Duarte
 *
 */

import com.yahoo.search.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.LinkedList;

import util.io.URLInput;
import util.parser.JsonParser;

public class YahooQuery {

	public static LinkedList<WebResult> yahooQuery(String query, int num_results) {

		LinkedList<WebResult> res = new LinkedList<WebResult>();

		// Create the search client. Pass it your application ID.
		SearchClient client = new SearchClient(
				"6xNO3c3V34HyFl_EfWpksJjBXAc4WvA2yyLOL3FrTg704WVE4UTu0OCD7eBOFUn8");

		WebSearchRequest request = new WebSearchRequest(query);
		request.setResults(num_results);
		request.setAdultOk(true);

		try {
			// Execute the search.
			WebSearchResults results = client.webSearch(request);

			// Iterate over the results.
			for (int i = 0; i < results.listResults().length && i < num_results; i++) {
				WebSearchResult result = results.listResults()[i];

				WebResult temp = new WebResult();

				temp.setEngine(WebResult.YAHOO);
				temp.setRank(i+1);	
				temp.setSnippet(result.getSummary());
				temp.setTitle(result.getTitle());
				temp.setUrl(result.getUrl());
				
				
				//delicious info
				DeliciousURLInfo del =  JsonParser.parseDeliciousInfoFromURL(result.getUrl().trim());
				temp.setDelicious(del);
			
				
				res.add(temp);

			}
		} catch (IOException e) {
			// Most likely a network exception of some sort.
			System.err.println("Error calling Yahoo! Search Service: "
					+ e.toString());
			e.printStackTrace(System.err);
		} catch (SearchException e) {
			// An issue with the XML or with the service.
			System.err.println("Error calling Yahoo! Search Service: "
					+ e.toString());
			e.printStackTrace(System.err);
		}

		return res;
	}
	
	
	
	public static LinkedList<String> getRelatedSearches(String query)
			throws UnsupportedEncodingException {

		String url = "http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?appid="
				+ Constants.YAHOO_ID
				+ "&query="
				+ URLEncoder.encode(query, "utf8");
		LinkedList<String> set = new LinkedList<String>();

		String post = URLInput.readFromURL(url);

		String lines[] = post.split("\n");
		for (int i = 0; i < lines.length; i++) {
			if (lines[i].contains("<Result>")) {

				String temp = lines[i].replaceFirst("\\s+", "");
				temp = temp.replace("<Result>", "");
				temp = temp.replace("</Result>", "");

			//	System.out.println(temp);

				set.add(temp);

			}

		}

		return set;
	}

	public static void makeYahooQuery(String query) {

		// Create the search client. Pass it your application ID.
		SearchClient client = new SearchClient(
				"6xNO3c3V34HyFl_EfWpksJjBXAc4WvA2yyLOL3FrTg704WVE4UTu0OCD7eBOFUn8");

		// Create the web search request. In this case we're searching for
		// java-related hits.
		WebSearchRequest request = new WebSearchRequest(query);

		try {
			// Execute the search.

			WebSearchResults results = client.webSearch(request);

			// Print out how many hits were found.
			System.out.println("Found " + results.getTotalResultsAvailable()
					+ " hits for java! Displaying the first "
					+ results.getTotalResultsReturned() + ".");

			// Iterate over the results.
			for (int i = 0; i < results.listResults().length; i++) {
				WebSearchResult result = results.listResults()[i];

				// Print out the document title and URL.
				System.out.println("   " + (i + 1) + ": " + result.getTitle()
						+ " - " + result.getUrl());
			}
		} catch (IOException e) {
			// Most likely a network exception of some sort.
			System.err.println("Error calling Yahoo! Search Service: "
					+ e.toString());
			e.printStackTrace(System.err);
		} catch (SearchException e) {
			// An issue with the XML or with the service.
			System.err.println("Error calling Yahoo! Search Service: "
					+ e.toString());
			e.printStackTrace(System.err);
		}
	}

	public static void main(String[] args) {
	//	System.out.println(yahooQuery("dinosaurs for kisd", 60).size());
		
		System.out.println(	URLEncoder.encode("buenos dias para ninos"));
		
		try {
			YahooQuery.getRelatedSearches("learn spanish for kids");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}